package com.demo.amusic;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.demo.amusic.dao.MusicDao;
import com.demo.amusic.entity.Music;
import com.demo.amusic.util.Authentication;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    protected SeekBar seekBar;//进度条
    private Timer timer;//定时器
    protected TextView tv_start;//开始时间
    protected TextView tv_end;//结束时间
    private TextView tv_main;
    private EditText et_idcard, et_name;
    private Button btn_test;
    private boolean isSeekbarChaning;//互斥变量，防止进度条和定时器冲突。
    private ImageView btn_play, btn_last, btn_next, btn_list;//播放，上一曲，下一曲
    private List<Music> list;//歌曲列表


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initData();
        initService();
    }

    private void initData() {
        //初始化测试数据
        MusicDao.getInstance(this).addOrUpdata(new Music("云烟成雨","房东的猫","513360721","",0));
        MusicDao.getInstance(this).addOrUpdata(new Music("小雨天气【抖音女声版】","","1887315860","",0));
        MusicDao.getInstance(this).addOrUpdata(new Music("只要为你活一天","","35288859","",0));
        MusicDao.getInstance(this).addOrUpdata(new Music("夏天的风","","1436709403","",0));
        long a = MusicDao.getInstance(this).addOrUpdata(new Music("愿你被岁月温柔对待","","1384026889","",0));
        list = MusicDao.getInstance(this).list();
    }

    private void initService() {
        AudioPlayer.getInstance().init();//初始化
        AudioPlayer.getInstance().setQueueAndIndex(list, 0);
        PlayerService.startPlayerService();

        BasePlayReceiver.registerReceiver(this, new BasePlayReceiver() {
            @Override
            protected void onInitSource(String source) {

            }

            @Override
            protected void onPrepared() {

            }

            @Override
            protected void onCompletion() {
                //播放完成
                AudioPlayer.getInstance().next();
            }

            @Override
            protected void onPlayStatus() {
                updateUI();
                //播放状态的改变
                if (AudioPlayer.getInstance().getStatus() == ManagedMediaPlayer.Status.STARTED){//开始
                    btn_play.setImageDrawable(getResources().getDrawable(R.drawable.pause));
                }else if (AudioPlayer.getInstance().getStatus() == ManagedMediaPlayer.Status.PAUSED){//暂停
                    btn_play.setImageDrawable(getResources().getDrawable(R.drawable.play));
                }else if (AudioPlayer.getInstance().getStatus() == ManagedMediaPlayer.Status.STOPPED){//停止
                    btn_play.setImageDrawable(getResources().getDrawable(R.drawable.play));
                }
            }

            @Override
            protected void onBufferingUpdate(int percent) {

            }

            @Override
            protected void onError(int what, int extra) {
                AudioPlayer.getInstance().release();
                PlayerService.startPlayerService();
            }
        });
    }


    public void updateUI() {
        int duration = AudioPlayer.getInstance().getDuration();//获取音乐总时间
        Log.e("进度条", "当前总时长：" + duration);
        seekBar.setMax(duration);//将音乐总时间设置为Seekbar的最大值，这里如果直接设置的话很可能会因为异步网络问题，在未加载完成时取到总长为0的情况，所以需要在异步加载完成的时候重新设置一下最大时长。
        timer = new Timer();//时间监听器
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                if (!isSeekbarChaning) {
                    try {
                        seekBar.setProgress(AudioPlayer.getInstance().getCurrentPosition());
                    } catch (Exception e) {

                    }

                }
            }
        }, 0, 50);
    }
    public void init() {
        seekBar = (SeekBar) findViewById(R.id.seekbar);
        tv_start = (TextView) findViewById(R.id.tv_leftTime);
        tv_end = (TextView) findViewById(R.id.tv_rightTime);
        tv_main = (TextView) findViewById(R.id.main_text);
        btn_play = (ImageView) findViewById(R.id.play);
        btn_last = (ImageView) findViewById(R.id.last);
        btn_next = (ImageView) findViewById(R.id.next);
        btn_list = (ImageView) findViewById(R.id.list);
        et_name = (EditText) findViewById(R.id.main_name);
        et_idcard = (EditText) findViewById(R.id.main_idcord);
        btn_test = (Button) findViewById(R.id.btn_test);



        btn_play.setOnClickListener(listener);
        btn_next.setOnClickListener(listener);
        btn_last.setOnClickListener(listener);
        btn_list.setOnClickListener(listener);
        btn_test.setOnClickListener(listener);

        //绑定监听器，监听拖动到指定位置
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int duration2 = AudioPlayer.getInstance().getDuration() / 1000;//获取音乐总时长
                int position = AudioPlayer.getInstance().getCurrentPosition();//获取当前播放的位置
                tv_start.setText(calculateTime(position / 1000));//开始时间
                tv_end.setText(calculateTime(duration2));//总时长
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekbarChaning = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekbarChaning = false;
                AudioPlayer.getInstance().seekTo(seekBar.getProgress());//在当前位置播放
                tv_start.setText(calculateTime(AudioPlayer.getInstance().getCurrentPosition() / 1000));
            }
        });

    }


    //自定义点击监听按钮
    private View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.play:
                    play();
                    break;
                case R.id.last:
                    AudioPlayer.getInstance().previous();
                    break;
                case R.id.next:
                    AudioPlayer.getInstance().next();
                    break;
                case R.id.list:
                    startActivity(new Intent(MainActivity.this,PlayingList.class));
                    break;
                case R.id.btn_test:
                    test();
                    break;
            }

        }
    };

    private void test(){
        //测试身份认证
        try {
            tv_main.setText("请稍后...");
            String idcard = et_idcard.getText().toString();
            String name = et_name.getText().toString();
            Authentication.AuthenticationResult result = Authentication.send(idcard,name);

            tv_main.setText(result.getPass() + "\n" + result.getMsg());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void play() {
        Log.e("pos", "play");
        if (AudioPlayer.getInstance().getStatus() == ManagedMediaPlayer.Status.STARTED) {
            AudioPlayer.getInstance().pause();
            Toast.makeText(this, "暂停播放", Toast.LENGTH_SHORT).show();
        } else if (AudioPlayer.getInstance().getStatus() == ManagedMediaPlayer.Status.PAUSED){
            AudioPlayer.getInstance().start();
            Toast.makeText(this, "继续播放", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //计算播放时间
    public String calculateTime(int time) {
        int minute;
        int second;
        if (time > 60) {
            minute = time / 60;
            second = time % 60;
            //分钟再0~9
            if (minute >= 0 && minute < 10) {
                //判断秒
                if (second >= 0 && second < 10) {
                    return "0" + minute + ":" + "0" + second;
                } else {
                    return "0" + minute + ":" + second;
                }
            } else {
                //分钟大于10再判断秒
                if (second >= 0 && second < 10) {
                    return minute + ":" + "0" + second;
                } else {
                    return minute + ":" + second;
                }
            }
        } else if (time < 60) {
            second = time;
            if (second >= 0 && second < 10) {
                return "00:" + "0" + second;
            } else {
                return "00:" + second;
            }
        } else if (time == 60) {
            return "01:00";
        }
        return null;
    }
}